package lk.controller;

import lk.exception.ResponseCodeContants;
import lk.exception.RestfulRecord;
import lk.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;

/**
 * 文件操作控制层接口
 */
@Controller
@RequestMapping("/file")
public class FileController {

    private FileService fileService;

    @Autowired
    public FileController(FileService fileService) {
        this.fileService = fileService;
    }

    /**
     * 文件上传
     *
     * @param file       文件本身
     * @param uploadType 文件上传类型
     * @return 是否成功
     */
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public RestfulRecord upload(MultipartFile file,
                                @RequestParam(value = "uploadType", required = false) Character uploadType) {
        RestfulRecord restfulRecord;
        try {
            restfulRecord = fileService.upload(file, uploadType);
        } catch (Exception e) {
            e.printStackTrace();
            restfulRecord = new RestfulRecord(ResponseCodeContants.ERROR_CODE, "文件上传失败");
        }
        return restfulRecord;
    }

    /**
     * 文件下载
     *
     * @param fileId   文件ID
     * @param response 下载
     */
    @RequestMapping(value = "/download", method = RequestMethod.GET)
    @ResponseBody
    public void download( @RequestParam(value = "fileId") String fileId, HttpServletResponse response) {
        try {
            fileService.download(fileId, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
